// directives/loading.js
const removeOverlay = (el) => {
    if (el._loadingOverlay) {
        if (el._loadingOverlay.dataset.removing === 'true') return;

        el._loadingOverlay.dataset.removing = 'true';
        el._loadingOverlay.style.transition = 'opacity 0.3s ease';
        el._loadingOverlay.style.opacity = '0';

        setTimeout(() => {
            if (el._loadingOverlay?.parentNode === document.body) {
                document.body.removeChild(el._loadingOverlay);
                document.body.style.overflow = '';
            }
            delete el._loadingOverlay;
            delete el._loadingStartTime;
            delete el._loadingMinDuration;
        }, 300);
    }
};

export const loadingDirective = {
    beforeMount(el, binding) {
        if (el._loadingOverlay) {
            removeOverlay(el);
        }

        const overlay = document.createElement('div');
        overlay.className = 'global-loading-overlay';
        overlay.innerHTML = binding.value?.template || `
      <div class="loading-content">
      </div>
    `;

        document.body.appendChild(overlay);
        document.body.style.overflow = 'hidden';
        el._loadingOverlay = overlay;
        el._loadingStartTime = Date.now();
        el._loadingMinDuration = binding.value?.minDuration || 300;
    },
    mounted(el) {
        const elapsed = Date.now() - el._loadingStartTime;
        const remaining = el._loadingMinDuration - elapsed;

        if (remaining > 0) {
            setTimeout(() => removeOverlay(el), remaining);
        } else {
            removeOverlay(el);
        }
    },
    updated(el, binding) {
        if (binding.oldValue !== binding.value) {
            this.beforeMount(el, binding);
        }
    },
    beforeUnmount(el) {
        removeOverlay(el);
    }
};
